package cn.com.nxt.txb.model;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;

/**
 * Created by lt on 2017/5/19.
 * CodeOK = 10000 //成功 CodeUserHasExist = 10001 // 用户名存在 CodeUserPasswordErrror = 10002 //用户密码或者用户名有错误 CodeIntervalException = 10003 // 内部异常 CodeUserNoAuth = 10004 // 用户无企业管理员权限 CodePareamException = 10005 //参数异常
 */

public class BaseModel implements Serializable {
    private static final long serialVersionUID = 1L;
    private String  code;  // 和状态码保持一致 参考错误码定义,
    private String  msg;     // 成功success,否则错误原因
    private String  data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public static BaseModel parseResult(String result){
        JSONObject obj= null;
        try {
            obj = new JSONObject(result);
        } catch (JSONException e) {
            return null;
        }
        BaseModel model=new BaseModel();
        model.setCode(obj.optString("code"));
        model.setMsg(obj.optString("msg"));
        model.setData(obj.optString("data"));
        return model;
    }

    public static <T> T parseToT(String str,Class<T> cla) {
        try {
           // JSONObject jo = new JSONObject(str);
           // code = jo.getInt("ResultCode");
//            Field[] fiels = cla.getDeclaredFields();
//            for (Field f:fiels){
//                String name = f.getName();
//                Log.v("111","name--"+name);
//                if (name.equals("data")){
//                    Class c = f.getType();
//                    Log.v("111","type--"+c.getName());
//                }
//            }

            return new Gson().fromJson(str, cla);
        } catch (Exception e) {
            try {
                if(str.contains("\"data\":{}}")){
                    str = str.replace("\"data\":{}}", "\"data\":[]}");
                }else{
                    str = str.replace("\"data\":[]}", "\"data\":{}}");
                }

                return new Gson().fromJson(str, cla);
            }catch (Exception ee){
                ee.printStackTrace();
                return null;
            }
            //e.printStackTrace();
            //return null;
        }
    }

}
